package com.elder.business.service.impl;

import java.lang.annotation.Target;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.elder.business.domain.HealthCheckRecords;
import com.elder.business.domain.MemberInfo;
import com.elder.business.domain.MemberLeaveRecord;
import com.elder.business.domain.MemberLeaveRecordDTO;
import com.elder.business.mapper.MemberInfoMapper;
import com.elder.business.mapper.MemberLeaveRecordMapper;
import com.elder.business.service.IMemberLeaveRecordService;
import com.elder.common.core.page.TableDataInfo;
import com.elder.common.enums.ApplyStatus;
import com.elder.common.enums.CheckUpType;
import com.elder.common.enums.WorkState;
import com.elder.common.utils.DateUtils;
import com.elder.common.utils.StringNewUtils;
import com.elder.common.utils.bean.BeanUtils;
import com.elder.common.utils.uuid.SnowGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 员工请假Service业务层处理
 * 
 * @author elder
 * @date 2024-04-13
 */
@Service
public class MemberLeaveRecordServiceImpl implements IMemberLeaveRecordService
{
    @Autowired
    private MemberLeaveRecordMapper memberLeaveRecordMapper;
    @Autowired
    private MemberInfoMapper memberInfoMapper;

    /**
     * 查询员工请假
     * 
     * @param memberId 员工请假主键
     * @return 员工请假
     */
    @Override
    public JSONObject selectMemberLeaveRecordByLeaveId(Long leaveId)
    {
        MemberLeaveRecord v = memberLeaveRecordMapper.selectMemberLeaveRecordByLeaveId(leaveId);
        MemberInfo member = Objects.isNull(v.getMemberId())?null:memberInfoMapper.getMemberByMemberId(v.getMemberId());
        JSONObject obj = new JSONObject();
        obj.put("leaveId", StringNewUtils.formatStr(v.getLeaveId()));
        obj.put("memberId", StringNewUtils.formatStr(v.getMemberId()));
        obj.put("memberName", Objects.isNull(member) ? "" : member.getMemberName());
        obj.put("title", v.getTitle());
        obj.put("reason", v.getReason());
        obj.put("leaveTime", DateUtils.dateStrMIAO(v.getLeaveTime()));
        obj.put("backTime", DateUtils.dateStrMIAO(v.getBackTime()));
        obj.put("state", ApplyStatus.getCnName(v.getState()));
        obj.put("notes", v.getNotes());
        return obj;
    }

    /**
     * 查询员工请假列表
     * 
     * @param memberLeaveRecord 员工请假
     * @return 员工请假
     */
    @Override
    public List<MemberLeaveRecord> selectMemberLeaveRecordList(MemberLeaveRecord memberLeaveRecord)
    {
        return memberLeaveRecordMapper.selectMemberLeaveRecordList(memberLeaveRecord);
    }

    /**
     * 新增员工请假
     * 
     * @param memberLeaveDTO 员工请假
     * @return 结果
     */
    @Override
    public int insertMemberLeaveRecord(MemberLeaveRecordDTO memberLeaveDTO)
    {
        MemberLeaveRecord memberLeaveRecord = new MemberLeaveRecord();
        BeanUtils.copyProperties(memberLeaveDTO,memberLeaveRecord);
        memberLeaveRecord.setLeaveId(SnowGenerator.getId());
        memberLeaveRecord.setLeaveTime(DateUtils.getDateSeconds(memberLeaveDTO.getLeaveTime()));
        memberLeaveRecord.setBackTime(DateUtils.getDateSeconds(memberLeaveDTO.getBackTime()));
        memberLeaveRecord.setState(ApplyStatus.APPLUING.getValue());
        memberLeaveRecord.setCreateTime(DateUtils.getLongTime());
        return memberLeaveRecordMapper.insertMemberLeaveRecord(memberLeaveRecord);
    }

    /**
     * 修改员工请假
     * 
     * @param memberLeaveRecord 员工请假
     * @return 结果
     */
    @Override
    public int updateMemberLeaveRecord(MemberLeaveRecord memberLeaveRecord)
    {
        return memberLeaveRecordMapper.updateMemberLeaveRecord(memberLeaveRecord);
    }

    /**
     * 批量删除员工请假
     * 
     * @param memberIds 需要删除的员工请假主键
     * @return 结果
     */
    @Override
    public int deleteMemberLeaveRecordByLeaveIds(Long[] memberIds)
    {
        return memberLeaveRecordMapper.deleteMemberLeaveRecordByMemberIds(memberIds);
    }

    /**
     * 删除员工请假信息
     * 
     * @param memberId 员工请假主键
     * @return 结果
     */
    @Override
    public int deleteMemberLeaveRecordByLeaveId(Long memberId)
    {
        return memberLeaveRecordMapper.deleteMemberLeaveRecordByMemberId(memberId);
    }

    @Override
    public TableDataInfo getMemberLeaveRecordList(String memberName,String startTime, String endTime, String status, Integer pageNum, Integer pageSize) {
        Integer applyStatus = null;
        if(status != null){
            applyStatus = ApplyStatus.getValue(status);
        }
        //时间处理
        Long daystartTime = null;
        Long dayendTime = null;
        if(!StringNewUtils.isEmpty(startTime)&& !StringNewUtils.isEmpty(endTime)){
            Long currentTime = DateUtils.getTargetDateSeconds(startTime);
            Long endCurrentTime = DateUtils.getTargetDateSeconds(endTime);
            daystartTime = DateUtils.getDayStartTime(currentTime);
            dayendTime = DateUtils.getDayEndTime(endCurrentTime);
        }
        List<Long> memberIds = StringNewUtils.isEmpty(memberName)?null:memberInfoMapper.getMemberListByMemberName(memberName);
        //分页
        PageHelper.startPage(pageNum, pageSize);
        List<MemberLeaveRecord> list = memberLeaveRecordMapper.getMemberLeaveRecordList(memberIds,applyStatus,daystartTime,dayendTime);
        PageInfo<MemberLeaveRecord> pageInfo = new PageInfo<>(list);
        List<MemberLeaveRecord> memberLeaveRecordList = pageInfo.getList();
        List<Long> memberIdList = memberLeaveRecordList.stream().map(MemberLeaveRecord::getMemberId).collect(Collectors.toList());
        Map<Long,MemberInfo> memberMap = CollectionUtils.isEmpty(memberIdList)?new HashMap<>():(memberInfoMapper.getMemberDept(memberIdList)
                .stream().collect(Collectors.toMap(MemberInfo::getMemberId, Function.identity())));
        List<JSONObject> objectList = memberLeaveRecordList.stream().map(v -> {
            JSONObject obj = new JSONObject();
            obj.put("leaveId", StringNewUtils.formatStr(v.getLeaveId()));
            obj.put("memberId", StringNewUtils.formatStr(v.getMemberId()));
            if(Objects.isNull(memberMap.get(v.getMemberId()))){
                obj.put("deptId","");
                obj.put("deptName","");
                obj.put("memberName", "");
            }else {
                obj.put("deptId", memberMap.get(v.getMemberId()).getDeptId());
                obj.put("deptName", memberMap.get(v.getMemberId()).getDeptName());
                obj.put("memberName", memberMap.get(v.getMemberId()).getMemberName());
            }
            obj.put("title", v.getTitle());
            obj.put("reason", v.getReason());
            obj.put("leaveTime", DateUtils.dateStrMIAO(v.getLeaveTime()));
            obj.put("backTime", DateUtils.dateStrMIAO(v.getBackTime()));
            obj.put("state", ApplyStatus.getCnName(v.getState()));
            obj.put("notes", v.getNotes());
            return obj;
        }).collect(Collectors.toList());
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(200);
        dataInfo.setTotal(pageInfo.getTotal());
        dataInfo.setRows(objectList);
        return dataInfo;
    }

    @Override
    public TableDataInfo getOneMemberLeaveRecordList(Long userId,String startTime, String endTime, String status, Integer pageNum, Integer pageSize) {
        MemberInfo member = memberInfoMapper.getMember(userId);
        Long memberId = member.getMemberId();
        Integer applyStatus = null;
        if(status != null){
            applyStatus = ApplyStatus.getValue(status);
        }
        //时间处理
        Long daystartTime = null;
        Long dayendTime = null;
        if(!StringNewUtils.isEmpty(startTime)&& !StringNewUtils.isEmpty(endTime)){
            Long currentTime = DateUtils.getTargetDateSeconds(startTime);
            Long endCurrentTime = DateUtils.getTargetDateSeconds(endTime);
            daystartTime = DateUtils.getDayStartTime(currentTime);
            dayendTime = DateUtils.getDayEndTime(endCurrentTime);
        }
        //分页
        PageHelper.startPage(pageNum, pageSize);
        List<MemberLeaveRecord> list = memberLeaveRecordMapper.getMemberLeaveRecordList(Arrays.asList(memberId),applyStatus,daystartTime,dayendTime);
        PageInfo<MemberLeaveRecord> pageInfo = new PageInfo<>(list);
        List<MemberLeaveRecord> memberLeaveRecordList = pageInfo.getList();
        List<JSONObject> objectList = memberLeaveRecordList.stream().map(v -> {
            JSONObject obj = new JSONObject();
            obj.put("leaveId", StringNewUtils.formatStr(v.getLeaveId()));
            obj.put("memberId", StringNewUtils.formatStr(v.getMemberId()));
            obj.put("memberName", Objects.isNull(member) ? "" : member.getMemberName());
            obj.put("title", v.getTitle());
            obj.put("reason", v.getReason());
            obj.put("leaveTime", DateUtils.dateStrMIAO(v.getLeaveTime()));
            obj.put("backTime", DateUtils.dateStrMIAO(v.getBackTime()));
            obj.put("state", ApplyStatus.getCnName(v.getState()));
            obj.put("notes", v.getNotes());
            return obj;
        }).collect(Collectors.toList());
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(200);
        dataInfo.setTotal(pageInfo.getTotal());
        dataInfo.setRows(objectList);
        return dataInfo;
    }

    @Override
    @Transactional
    public int approvalMemberLeave(Long leaveId, Long memberId, String status, String notes) {
        memberLeaveRecordMapper.updateMemberLeave(leaveId,ApplyStatus.getValue(status),notes);
        //审批通过修改上班状态
        if(Objects.equals(status,ApplyStatus.APPLY_PASS.getDisplayName())) {
            memberInfoMapper.updateMemberState(memberId, WorkState.ASK_LEAVE.getValue());
        }
        return 1;
    }

}
